<?php

namespace App\Services\Assess;

use App\Models\Assess\SendLogModel;
use App\Models\Assess\VisitorsRecordModel;
use App\Models\Assess\VisitorsRecordOnlineModel;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\Config\Definition\Exception\Exception;

class SendLogService extends BaseService
{

    //发送来源 发送日志需要记录(1:激活买家,2:激活失败,3:激活异常,4:关闭引导,5:用户注册-已激活,6:选择礼品但未留评,
    //7:激活留中差评,8:激活留好评,9:中低评分用户,10:高评分用户,11:高评价已匹配用户,12:高评价未匹配用户)
    const  SEND_SOURCE_ACTIVATE = 1;
    const  SEND_SOURCE_ACTIVATE_FAIL = 2;
    const  SEND_SOURCE_ACTIVATE_EXCEPTION = 3;
    const  SEND_CLOSE_GUIDE = 4;
    const SEND_CLOSE_ACTIVATE =5;
    const SEND_CLOSE_NO_COMMENT =6;
    const SEND_CLOSE_BAD_REVIEWS =7;
    const SEND_CLOSE_FAVORABLE_COMMENT =8;
    const SEND_CLOSE_LOW_RATING =9;
    const SEND_CLOSE_HEIGHT_RATING =10;
    const SEND_CLOSE_HEIGHT_RATING_YES =11;
    const SEND_CLOSE_HEIGHT_RATING_NO =12;

    public $sendSource = [
        self::SEND_SOURCE_ACTIVATE => '激活买家',
        self::SEND_SOURCE_ACTIVATE_FAIL => '激活失败',
        self::SEND_SOURCE_ACTIVATE_EXCEPTION => '激活异常',
        self::SEND_CLOSE_GUIDE => '关闭引导',
        self::SEND_CLOSE_ACTIVATE => '用户注册-已激活',
        self::SEND_CLOSE_NO_COMMENT => '选择礼品但未留评',
        self::SEND_CLOSE_BAD_REVIEWS => '激活留中差评',
        self::SEND_CLOSE_FAVORABLE_COMMENT => '激活留好评',
        self::SEND_CLOSE_LOW_RATING => '中低评分用户',
        self::SEND_CLOSE_HEIGHT_RATING => '高评分用户',
        self::SEND_CLOSE_HEIGHT_RATING_YES => '高评价已匹配用户',
        self::SEND_CLOSE_HEIGHT_RATING_NO => '高评价未匹配用户',

    ];

    //状态(1:待发送,2:发送成功,3:已打开,4:已点击链接,5:发送失败)
    const STATUS_NEW = 1;
    const STATUS_SEND_SUCCESS = 2;
    const STATUS_OPEN = 3;
    const STATUS_CLICK_LINK = 4;
    const STATSU_SEND_FAIL = 5;

    public $statusMapping = [
        self::STATUS_NEW => '待发送',
        self::STATUS_SEND_SUCCESS => '发送成功',
        self::STATUS_OPEN => '已打开',
        self::STATUS_CLICK_LINK => '已点击链接',
        self::STATSU_SEND_FAIL => '发送失败'
    ];

    //发送日志类型1:系统生成,2:业务手动操作
    const SEND_EMAIL_TYPE_SYSTEM=1;
    const SEND_EMAIL_TYPE_HAND=2;

    public $sendEmailType = [
        self::SEND_EMAIL_TYPE_SYSTEM=>'系统发送',
        self::SEND_EMAIL_TYPE_HAND=>'手动发送'
    ];


    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new SendLogModel();
    }

    /**
     * @Notes:获取界面搜索配置
     * @Interface getSendLogConfig
     * @return array
     * @author: wuyu
     * @Time: 2023/5/15   17:30
     */
    public function getSendLogConfig()
    {
        $config = [];
        $config['send_source_list'] = $this->sendSource;
        $config['status_list'] = $this->statusMapping;
        $config['type_list'] = $this->sendEmailType;
        return $config;
    }


    /**
     * @Notes:获取日志表数据
     * @Interface getList
     * @return array
     * @author: wuyu
     * @Time: 2023/5/15   17:39
     */
    public function getList()
    {
        $param = request()->all();
        // 查询条件
        $map[] = ['mark','=',1];
        $email = getter($param, 'email', '');
        $receiveEmail = getter($param, 'receive_email', '');
        $templateType = getter($param, 'template_type', '');
        $createUser = getter($param, 'create_user', '');
        $status = getter($param, 'status', '');
        $source = getter($param, 'source', '');
        $orderId = getter($param, 'order_id', '');
        $sku = getter($param, "sku",'');
        $type = getter($param, 'type', '');
        $sort = getter($param, 'sort', 'create_time');
        $order = getter($param, 'order', 'desc');
        $page_size = getter($param, 'page', 1);
        $limit = getter($param, 'limit', 10);

        $skuStr = str_replace(['；', ',', '，',"\r\n", "\r", "\n"], ';', $sku);
        if (!empty($skuStr)) $skuArr = array_unique(explode(';', $skuStr));

        if (!empty($email)) $map[] = ['email', 'like', "%{$email}%"];
        if (!empty($receiveEmail)) $map[] = ['receive_email', 'like', "%{$receiveEmail}%"];
        if (!empty($templateType)) $map[] = ['type', '=', $templateType];
        if (!empty($orderId)) $map[] = ['order_id', '=', $orderId];
        if (!empty($createUser)) $map[] = ['create_user', '=', $createUser];
        if (!empty($status)) $map[] = ['status', '=', $status];
        if (!empty($source)) $map[] = ['source', '=', $source];
        if (!empty($type)) $map[] = ['type', '=', $type];
        $offset = ($page_size - 1) * $limit;

//        $userList = CommonService::userAuth();
        $skuAuth = CommonService::skuAuth();

        $model = $this->model->where($map);
        $model2 = $this->model->where($map);
        if (!empty($skuArr)){
            $model->whereIn('sku',$skuArr);
            $model2->whereIn('sku',$skuArr);
        }
        if (!empty($skuAuth) && empty($skuArr)){
            $model->whereIn('sku',$skuAuth);
            $model2->whereIn('sku',$skuAuth);
        }
        $list = $model
            ->orderBy($sort, $order)
            ->offset($offset)
            ->limit(PERPAGE)
            ->get()->toArray();
        $count = $model2->count();

        foreach ($list as $key => $val) {
            $info = $this->model->getInfo($val['id']);
            $val = array_merge($val,$info);
            $val['status'] = $this->statusMapping[$val['status']] ?? '';
            $val['source'] = $this->sendSource[$val['source']] ?? '';
            $val['send_success_time'] = !empty($val['send_success_time']) ? date('Y-m-d H:i',$val['send_success_time'])  : '-';
            $val['end_open_time'] = !empty($val['end_open_time']) ? date('Y-m-d H:i',$val['end_open_time'])  : '-';
            $val['click_link_time'] = !empty($val['click_link_time']) ? date('Y-m-d H:i',$val['click_link_time'])  : '-';

            $connect = explode('<img width="1px" height="1px" src="https://www.warrantysystem.top:168',$val['content']);
            if (!empty($connect) && count($connect) >1) $val['content'] = $connect[0];
            //获取日志类型
            $val['type_html'] = $this->sendEmailType[$val['type']] ?? '';
            $list[$key] = $val;
        }
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

    }


    /**
     * @Notes:用户收到邮箱后打开回访
     * @Interface emailReady
     * @author: wuyu
     * @Time: 2023/6/2   10:26
     */
    public function emailReady()
    {
        $param = request()->all();
        Log::channel('emailLog')->debug('emailReady接受邮件请求成功:',['params' => $param]);
        $logId = $param['log_id'] ?? '';
        $statusPrefix = $param['status_prefix'] ?? '';

        if (empty($logId) || empty($statusPrefix)){
            return message('参数错误',false);
        }

        $logInfo = $this->model->getOne([
            ['id', '=', $logId],
            ['status', '=', $statusPrefix]
        ],'id,status');
        if (empty($logInfo)){
            Log::channel('emailLog')->debug('emailReady数据不存在:',['params' => $param]);
            return message('数据不存在',false);
        }
        $status = 0;
        switch ($statusPrefix){
            case 2:
                $status = 3;
                break;
            case 3:
                $status=4;
                break;
            case 4:
                $status=5;
                break;
        }
        if (!empty($status)){
            $LogData = [
                'status'=>$status,
                'end_open_time'=>time()
            ];
            $this->model->where('id','=',$logId)->update($LogData);
            $this->model->cacheReset($logId, $LogData, $logId);
        }

        return message("操作成功", true, []);

    }

    /**
     * @Notes:客户点击邮箱进行访问标记
     * @Interface emailClickLink
     * @return array
     * @author: wuyu
     * @Time: 2023/6/2   11:53
     */
    public function emailClickLink($param)
    {
        Log::channel('emailLog')->debug('emailReady接受邮件请求成功:',['params' => $param]);
        $logId = $param['log_id'] ?? '';

        if (empty($logId)){
            return message('参数错误',false);
        }

        $logInfo = $this->model->getOne([
            ['id', '=', $logId],
        ],'id,status');
        if (empty($logInfo)){
            Log::channel('emailLog')->debug('emailReady数据不存在:',['params' => $param]);
            return message('数据不存在',false);
        }
        $status = 4;

        if (!empty($status)){
            $LogData = [
                'status'=>$status,
                'click_link_time'=>time()
            ];
            $this->model->where('id','=',$logId)->update($LogData);
            $this->model->cacheReset($logId, $LogData, $logId);
        }

        return message("操作成功", true, []);

    }



    /**
     * @Notes:发送邮件记录信息
     * @Interface emailSendLog
     * @author: wuyu
     * @Time: 2023/5/15   15:12
     */
    public function emailSendLog($sendLogData)
    {

        return $this->model->insertGetId($sendLogData);
    }

    public function updateById($id,$data)
    {
        return $this->model->where('id','=',$id)->update($data);
    }


    /**
     * @Notes:检测访问日志ip是否正常客户
     * @Interface checkActivateIp
     * @param $params
     * @author: wuyu
     * @Time: 2023/7/27   12:03
     */
    public function checkActivateIp($params)
    {

            $ip = $params['ip'] ?? '';
            $startDate = $params['start_date'] ?? '';
            $endDate = $params['end_date'] ?? '';
            $VisitorsRecordOnlineModel = new VisitorsRecordOnlineModel();

            $model = $VisitorsRecordOnlineModel->where('mark','=',1)->where('ip_type','=',0)->where('check_num','<',5);
            if (!empty($ip)) $model->where('ip','=',$ip);
            if (!empty($startDate)) $model->where('create_time','>=',strtotime($startDate));
            if (!empty($endDate)) $model->where('create_time','<=',strtotime($endDate));
            $logData = $model->orderBy('id', 'desc')->get(['id','ip','ip_type','check_num'])->toArray();

            foreach ($logData as $val){

                try {
                    $redisKey = 'check:activate:ip:' . $val['id'];
                    if (Redis::get($redisKey)) {
                        continue;
                    }
                    Log::channel('checkActivateIp')->debug('ip正在检测中:'.$val['ip']);
                    //调用第三方平台 检测ip是否有标记
                    $ipApi = 'https://www.ipshudi.com/'.$val['ip'].'.htm';
                    ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)");
                    $html = file_get_contents($ipApi);

                    $updateData = [
                        'ip_type'=>1,
                        'check_num'=>$val['check_num']+1
                    ];
                    if (strpos($html,'Google蜘蛛') !==false ){
                        $updateData['ip_type'] = 2;
                        $updateData['mark'] = 0;
                    }elseif (strpos($html,'Bing蜘蛛') !==false){
                        $updateData['ip_type'] = 2;
                        $updateData['mark'] = 0;
                    }elseif (strpos($html,'中国') !==false && strpos($html,'阿里云') !==false && strpos($html,'数据中心') !==false){
                        $updateData['ip_type'] = 2;
                        $updateData['mark'] = 0;
                    }elseif (strpos($html,'中国') !==false && strpos($html,'城域网') !==false && strpos($html,'中国 广东省') !==false){
                        $updateData['ip_type'] = 2;
                        $updateData['mark'] = 0;
                    }elseif (strpos($html,'中国') !==false && strpos($html,'数据中心') !==false && strpos($html,'中国 广东省') !==false){
                        $updateData['ip_type'] = 2;
                        $updateData['mark'] = 0;
                    }elseif (strpos($html,'中国') !==false && strpos($html,'中国 广东省') ===false){
                        $updateData['ip_type'] = 2;
                        $updateData['mark'] = 0;
                    }elseif (strpos($html,'百慕大') !==false){
                        $updateData['ip_type'] = 2;
                        $updateData['mark'] = 0;
                    }

                } catch (\Exception $e) {
                    $updateData['ip_type'] = 0;
                    Log::channel('checkActivateIp')->debug('检查访客日志ip失败:'.$e->getMessage().' '.$e->getFile().' '.$e->getLine());
                }

                $VisitorsRecordOnlineModel->where('id','=',$val['id'])->update($updateData);
                $VisitorsRecordOnlineModel->cacheReset($val['id'], [], $val['id']); //清除缓存
                //存储并设置过期时间
                Redis::setex($redisKey, 15, 1);

                //设置休眠时间 防止过快调用第三方接口 被查杀
                sleep(30);
            }
    }


}
